package com.stark.commons.spring.web.boot.config;

import java.util.Collections;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.cloud.netflix.zuul.filters.route.RibbonCommandFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.stark.commons.spring.web.boot.properties.ZuulTimeoutProperties;
import com.stark.commons.spring.web.support.zuul.CustomHttpClientRibbonCommandFactory;
import com.stark.commons.spring.web.support.zuul.ZuulFallbackProvider;

/**
 * zuul 网关自动配置。
 * 
 * @author Ben
 * @since 1.0.0
 * @version 1.0.0
 * @see org.springframework.cloud.netflix.zuul.RibbonCommandFactoryConfiguration#RibbonCommandFactoryConfiguration()
 */
@Configuration
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass(name = {
		"org.springframework.cloud.netflix.zuul.filters.ZuulProperties"
})
@EnableConfigurationProperties(ZuulTimeoutProperties.class)
public class ZuulAutoConfig {
	
	@Autowired(required = false)
	private Set<FallbackProvider> zuulFallbackProviders = Collections.emptySet();
	
	@Bean
	public RibbonCommandFactory<?> ribbonCommandFactory(SpringClientFactory clientFactory, ZuulProperties zuulProperties, ZuulTimeoutProperties zuulTimeoutProperties) {
		return new CustomHttpClientRibbonCommandFactory(clientFactory, zuulProperties, zuulFallbackProviders, zuulTimeoutProperties);
	}
	
	@Bean
	@ConditionalOnMissingBean
	public FallbackProvider fallbackProvider() {
		return new ZuulFallbackProvider();
	}
	
}
